<template>
  <div class="exam-container">
    <el-card class="status-sidebar">
      <div class="sidebar-header">
        <i class="el-icon-s-data"></i>
        <h3>答题进度</h3>
      </div>
      <div class="question-status">
        <div
            v-for="(item, index) in tracker"
            :key="index"
            class="status-item"
            :class="{ answered: item.answered }"
            @click="scrollToQuestion(index)"
        >
          <span class="status-number">{{ index + 1 }}</span>
          <i v-if="item.answered" class="el-icon-check status-icon"></i>
          <i v-else class="el-icon-circle-check status-icon"></i>
        </div>
      </div>
    </el-card>
    <div class="content-wrapper">
    <div class="countdown-timer">
      <el-alert
          :title="countdownText"
          type="warning"
          :closable="false"
          :class="{ 'time-warning': totalTime <= 300 }"
      />
    </div>
    <!-- 试卷卡片 -->
    <el-card class="exam-card">
      <!-- 试卷标题区域 -->
      <div class="exam-header">
        <div class="title-decoration">
          <i class="el-icon-document-checked"></i>
          <h1>心理健康测评试卷</h1>
          <i class="el-icon-edit-outline"></i>
        </div>
        <div class="divider-line"></div>
      </div>

      <!-- 试题内容 -->
      <transition-group name="question-fade">
        <div v-for="(question, index) in form" :id="`question-${index}`" :key="question.id" class="question-item">
          <!-- 图片显示 -->
          <div v-if="question.img" class="question-image">
            <el-image
                style="width: 200px; height: 150px"
                :src="'http://localhost:8080/zcy/files/' + question.img"
                fit="contain"
                :preview-src-list="['http://localhost:8080/zcy/files/' + question.img]"
                class="image-box"
            >
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
                <p>图片加载失败</p>
              </div>
              <div slot="placeholder" class="image-loading">
                <i class="el-icon-loading"></i>
                <p>图片加载中...</p>
              </div>
            </el-image>
          </div>

          <!-- 题目内容 -->
          <div class="question-content">
            <h3 class="question-title">
              <span class="question-number">{{ index + 1 }}.</span>
              {{ question.title }}
            </h3>
            <el-radio-group
                v-model="question.answer"
                class="option-group"
            >
              <el-radio
                  v-for="(option, optIndex) in question.options"
                  :label="option"
                  :key="optIndex"
                  class="option-item"
              >
                <span class="option-mark">{{ String.fromCharCode(65 + optIndex) }}.</span>
                {{ option }}
              </el-radio>
            </el-radio-group>
          </div>
        </div>
      </transition-group>
    </el-card>

    <!-- 提交按钮 -->
    <div class="submit-section">
      <el-button
          type="primary"
          class="submit-btn"
          :loading="isSubmitting"
          @click="submit"
      >
        <i class="el-icon-upload2"></i>
        {{ isSubmitting ? '提交中...' : '提交试卷' }}
      </el-button>
    </div>
  </div>
  </div>
</template>

<script>
import request from "@/utils/request";

export default {
  data() {
    return {
      form: [],
      isSubmitting: false,
      totalTime: 1800,
      timer: null,
      activeQuestion: 0
    }
  },
  computed: {
    tracker() {
      return this.form.map(question => ({
        answered: !!question.answer
      }));
    },
    countdownText() {
      const minutes = Math.floor(this.totalTime / 60)
          .toString()
          .padStart(2, '0');
      const seconds = (this.totalTime % 60)
          .toString()
          .padStart(2, '0');
      return `剩余时间 ${minutes}:${seconds}`;
    }
  },
  created() {
    this.findBySearch();
    this.startTimer();
  },
  beforeDestroy() {
    this.clearTimer();
    window.removeEventListener('scroll', this.handleScroll);
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll);
  },
  methods: {
    handleScroll() {
      const questions = document.querySelectorAll('.question-item');
      const scrollPos = window.scrollY + 100;

      questions.forEach((question, index) => {
        const offsetTop = question.offsetTop;
        const height = question.offsetHeight;

        if (scrollPos >= offsetTop && scrollPos < (offsetTop + height)) {
          this.activeQuestion = index;
        }
      });
    },
    scrollToQuestion(index) {
      const questionId = `question-${index}`;
      const element = document.getElementById(questionId);
      if (element) {
        element.scrollIntoView({
          behavior: 'smooth',
          block: 'start'
        });
      }
    },
    startTimer() {
      this.timer = setInterval(() => {
        if (this.totalTime > 0) {
          this.totalTime--;
          if (this.totalTime === 300) {
            this.$notify({
              title: '时间提醒',
              message: '距离考试结束还有5分钟！',
              type: 'warning',
              duration: 5000
            });
          }
        } else {
          this.clearTimer();
          if (!this.isSubmitting) {
            this.$confirm('考试时间已结束，将自动提交试卷', '时间到', {
              confirmButtonText: '确定',
              showCancelButton: false,
              type: 'warning'
            }).then(() => {
              this.submit();
            }).catch(() => {
              this.submit();
            });
          }
        }
      }, 1000);
    },
    clearTimer() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },
    findBySearch() {
      request.get("/paper/findPaper").then(res => {
        if (res.code === '0') {
          this.form = res.data.map(item => ({
            ...item,
            // 确保每个题目都有唯一ID
            id: item.id || Math.random().toString(36).substr(2, 9)
          }));
        } else {
          this.showMessage(res.msg, 'error');
        }
      }).catch(error => {
        this.handleError(error);
      });
    },
    submit() {
      this.clearTimer();
      this.isSubmitting = true;
      request.post("/paper/examing", this.form).then(res => {
        if (res.code === '0') {
          this.showMessage(`提交成功，您的成绩是 ${res.data} 分！`, 'success');
          setTimeout(() => {
            this.$router.push("/home");
          }, 1500);
        }
      }).finally(() => {
        this.isSubmitting = false;
      });
    },
    showMessage(msg, type) {
      this.$message({
        message: msg,
        type: type,
        duration: 3000,
        showClose: true
      });
    },
    handleError(error) {
      console.error(error);
      this.showMessage('请求失败，请检查网络连接', 'error');
    }
  }
}
</script>

<style scoped lang="scss">
.exam-container {
  max-width: 1000px;
  margin: 20px auto;
  padding: 20px;
}

.exam-card {
  border-radius: 15px;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.08);
}

.exam-header {
  margin-bottom: 30px;

  .title-decoration {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 15px;
    margin-bottom: 20px;

    i {
      font-size: 32px;
      color: #409EFF;
    }

    h1 {
      color: #303133;
      margin: 0;
      font-size: 28px;
    }
  }

  .divider-line {
    height: 2px;
    background: linear-gradient(90deg, #409EFF 0%, #67C23A 100%);
    opacity: 0.2;
  }
}

.question-item {
  margin: 25px 0;
  padding: 20px;
  border-radius: 10px;
  transition: all 0.3s ease;
  background: rgba(250, 250, 255, 0.8);

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
  }
}

.question-image {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;

  .image-box {
    width: 100%;
    max-height: 300px;
    border-radius: 8px;
    transition: transform 0.3s ease;

    &:hover {
      transform: scale(1.02);
    }
  }

  .image-slot {
    height: 200px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f5f7fa;
    color: #909399;
    font-size: 24px;
  }
}

.question-content {
  .question-title {
    color: #303133;
    font-size: 18px;
    line-height: 1.6;
    margin-bottom: 15px;

    .question-number {
      color: #409EFF;
      margin-right: 8px;
    }
  }
}

.option-group {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.option-item {
  margin: 0;
  padding: 12px 20px;
  border-radius: 8px;
  transition: all 0.2s ease;
  border: 1px solid #ebeef5;

  &:hover {
    background: rgba(64, 158, 255, 0.05);
    border-color: #409EFF;
  }

  ::v-deep .el-radio__label {
    display: flex;
    align-items: center;
  }

  .option-mark {
    font-weight: bold;
    color: #67C23A;
    margin-right: 8px;
  }
}

.submit-section {
  text-align: center;
  margin: 30px 0;

  .submit-btn {
    padding: 15px 50px;
    font-size: 16px;
    border-radius: 25px;
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
    transition: transform 0.3s ease;

    &:hover {
      transform: translateY(-2px);
    }

    i {
      margin-right: 8px;
    }
  }
}

/* 过渡动画 */
.question-fade-enter-active,
.question-fade-leave-active {
  transition: opacity 0.5s, transform 0.5s;
}
.question-fade-enter,
.question-fade-leave-to {
  opacity: 0;
  transform: translateX(30px);
}

@media (max-width: 768px) {
  .exam-container {
    padding: 10px;
  }

  .question-image .image-box {
    max-height: 200px;
  }

  .question-title {
    font-size: 16px;
  }

  .submit-btn {
    width: 100%;
    padding: 12px 20px;
  }
}
.countdown-timer {
  position: fixed;
  right: 20px;
  top: 20px;
  z-index: 9999;
  min-width: 180px;
  text-align: center;
  animation: pulse 10s infinite;

  ::v-deep .el-alert {
    border-radius: 18px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

    &__title {
      font-size: 16px;
      font-weight: bold;
    }
  }

  .time-warning ::v-deep .el-alert__title {
    color: #e6a23c;
    animation: blink 1s infinite;
  }
}

@keyframes blink {
  50% { opacity: 0.6; }
}

@keyframes pulse {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.02); }
}

.exam-container {
  position: relative;
  padding-left: 100px; // 为侧边栏留出空间
}

.status-sidebar {
  position: fixed;
  left: 20px;
  top: 100px;
  width: 270px;
  height: calc(100vh - 150px); /* 限制高度 */
  overflow-y: auto; /* 添加垂直滚动 */
  z-index: 999;
  /* 添加滚动条美化 */
  &::-webkit-scrollbar {
    width: 6px;
  }
  &::-webkit-scrollbar-thumb {
    background: #c0c4cc;
    border-radius: 3px;
  }
  &::-webkit-scrollbar-track {
    background: #f5f7fa;
  }

  .sidebar-header {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    i {
      font-size: 24px;
      color: #409EFF;
      margin-right: 10px;
    }
    h3 {
      margin: 0;
      font-size: 18px;
      color: #303133;
    }
  }

  .question-status {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 10px;
  }

  .status-item {
    position: relative;
    width: 40px;
    height: 40px;
    border-radius: 8px;
    background: #f5f7fa;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;

    &:hover {
      transform: scale(1.1);
      box-shadow: 0 2px 6px rgba(0,0,0,0.1);
    }

    &.answered {
      background: #f0f9eb;
      .status-icon {
        color: #67C23A;
      }
    }

    .status-number {
      position: absolute;
      top: 2px;
      right: 2px;
      font-size: 12px;
      color: #909399;
    }

    .status-icon {
      font-size: 20px;
      color: #c0c4cc;
    }
  }
}


// 响应式调整
@media (max-width: 1200px) {
  .exam-container {
    padding-left: 0;
  }

  .status-sidebar {
    display: none; // 小屏幕隐藏侧边栏
  }
}
</style>